package com.fangyu.mall.service.impl;

import com.fangyu.mall.dao.UserMapper;
import com.fangyu.mall.pojo.User;
import com.fangyu.mall.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author fangyu
 * @version v1.0.0
 * @date 2020/3/8 11:41 下午
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) {
        // username不能重复
        if (userMapper.countByUsername(user.getUsername()) > 0) {
            throw new RuntimeException("该用户已注册");
        }
        // email不能重复
        if (userMapper.countByEmail(user.getEmail()) > 0) {
            throw new RuntimeException("该邮箱已注册");
        }

        // MD5摘要算法(Spring自带)
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        // 写入数据库
        int result = userMapper.insertSelective(user);
        if (result == 0) {
            throw new RuntimeException("注册失败!");
        }

    }

    @Override
    public void login() {

    }
}
